import requests
from lxml import etree

def spider_pic(pic_url):
    try:
        response = requests.get(pic_url)
        response.encoding = "utf-8"
        selector = etree.HTML(response.text)
        page_pic = selector.xpath('//img/@data-src')
        print(page_pic)
        try:
            c = 1
            global b
            b = 0
            while c < 101:
                b = b+1
                c = c+1
                print(page_pic[c-2], "{}".format(c-1))
                response = requests.get(page_pic[c])
                with open("This is page {} picture{}.png".format(i, b), "wb+") as e:
                    e.write(response.content)
        except:
            print("此图片不可下载")

    except:
        print("连接失败")

for i in range(4, 21):
    url = "https://alpha.wallhaven.cc/search?q=&categories=001&purity=100&topRange=1M&sorting=toplist&order=desc&page={}".format(i)
    spider_pic(url)
